<?php
class Captcha{
    protected $width;
    protected $height;
    protected $size;
    protected $res;
    protected $len = 4;
    protected $font;
    protected $code;
    public function __construct(int $width=100,int $height=30,int $size=20)
    {
        $this->width = $width;
        $this->height = $height;
        $this->size = $size;
        $this->font = realpath('Source.otf');
    }

    #对外公开的方法
    public function make(){
        #创建画布
        $res = imagecreatetruecolor($this->width,$this->height);
        imagefill($this->res=$res,0,0,imagecolorallocate($res,200,200,200));
        #绘制干扰点
        $this->pix();
        #绘制干扰线
        $this->line();
        #编写文字
        $this->text();
        #显示图像
        $this->render();
        return $this->code;
    }

    #编写文字
    public function text(){
        $text = '12qwertyuio350pfgh6789jklm4nbvcxz';
        for ($i = 0;$i<$this->len;$i++){
            $box = imagettfbbox($this->size,mt_rand(-20,20),$this->font,$text[$i]);
            $x = $this->width/$this->len*$i;
            $code = $text[mt_rand(0,$this->len)];
            imagettftext($this->res,$this->size,mt_rand(-20,20),$x,$this->height/2+($box[3]-$box[5])/2,$this->textColor(),$this->font,$code);
            $this->code.=$code;
        }
    }


    #将验证码写入文件中
    protected function putCodeToFile(){
        file_put_contents('code.txt',$this->code);
    }


    #获取验证码的值
    public function codeText(){
        return $this->code;
    }

    #绘制干扰点
    protected function pix(){
        for ($i=0;$i<200;$i++){
            imagesetpixel($this->res,mt_rand(0,$this->width),mt_rand(0,$this->height),$this->color());
        }
    }

    #绘制干扰线
    protected function line(){
        for($i=0;$i<5;$i++){
            imagesetthickness($this->res,mt_rand(1,3));
            imageline($this->res,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$this->color());
        }
    }


    #文字颜色
    protected function textColor(){
        return imagecolorallocate($this->res,mt_rand(50,150),mt_rand(50,150),mt_rand(50,150));
    }

    #绘制颜色
    protected function color(){
        return imagecolorallocate($this->res,mt_rand(100,200),mt_rand(100,200),mt_rand(100,200));
    }

    #显示图像
    protected function render(){
        header('Content-Type:image/png');
        imagepng($this->res);
        imagedestroy($this->res);
    }
}